package com.qianwei.footpath.manage;

import java.util.List;

public class BalanceAnalyzer {

    // 平衡能力结论枚举
    public enum BalanceResult {
        EXCELLENT,   // 优秀
        GOOD,        // 良好
        POOR,        // 差
        INVALID_DATA // 数据无效
    }

    // 核心分析方法
    public static BalanceResult analyzeBalance(List<Double> weightData) {
        // 数据有效性校验
        if (weightData == null || weightData.isEmpty()) {
            return BalanceResult.INVALID_DATA;
        }

        try {
            // 1. 计算基准体重（取前3秒稳定期数据，假设采样率20Hz：3s×20=60点）
            int initialWeightSampleSize = Math.min(weightData.size(), 60);
            double initialWeight = calculateAverage(weightData.subList(0, initialWeightSampleSize));

            // 2. 计算全程波动百分比
            double[] fluctuations = new double[weightData.size()];
            double maxInstantaneous = 0; // 最大瞬时波动

            for (int i = 0; i < weightData.size(); i++) {
                double fluctuation = Math.abs((weightData.get(i) - initialWeight) / initialWeight * 100);
                fluctuations[i] = fluctuation;
                if (fluctuation > maxInstantaneous) {
                    maxInstantaneous = fluctuation;
                }
            }

            // 3. 计算平均波动（标准差）
            double avgFluctuation = calculateStandardDeviation(fluctuations);

            // 4. 判断等级
            return evaluateBalanceLevel(avgFluctuation, maxInstantaneous);

        } catch (ArithmeticException e) {
            return BalanceResult.INVALID_DATA;
        }
    }

    // 评估等级规则
    private static BalanceResult evaluateBalanceLevel(double avgFluctuation, double maxInstantaneous) {
        // 优秀：平均波动 < 2% 且瞬时峰值 < 4%
        if (avgFluctuation < 2.0 && maxInstantaneous < 4.0) {
            return BalanceResult.EXCELLENT;
        }

        // 良好：平均波动 2-3% 且瞬时峰值 4-6%
        if (avgFluctuation <= 3.0 && maxInstantaneous <= 6.0) {
            return BalanceResult.GOOD;
        }

        // 差：超出上述范围
        return BalanceResult.POOR;
    }

    // 计算平均值
    private static double calculateAverage(List<Double> data) {
        double sum = 0;
        for (double value : data) {
            sum += value;
        }
        return sum / data.size();
    }

    // 计算标准差
    private static double calculateStandardDeviation(double[] data) {
        double mean = calculateAverage(data);
        double sumSquares = 0;

        for (double value : data) {
            sumSquares += Math.pow(value - mean, 2);
        }

        return Math.sqrt(sumSquares / data.length);
    }

    // 兼容List的泛型平均值计算（用于double[]）
    private static double calculateAverage(double[] data) {
        double sum = 0;
        for (double value : data) {
            sum += value;
        }
        return sum / data.length;
    }
}
